<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>超市账单管理系统</title>
    <style type="text/css">
        .el-header {
            background-color: #545c64;
        }

        .header-img {
            margin-top: 15px;
        }

        .face {
            margin-top: 5px;
            width: 40px;
            height: 40px;
            border-radius: 20px;
        }
        .el-dropdown-link {
            cursor: pointer;
            color: whitesmoke;
            line-height: 60px;
        }
        .el-icon-arrow-down {
            font-size: 12px;
        }
        .text{
            float: right;
        }
        .like {
            cursor: pointer;
            font-size: 25px;
            display: inline-block;
        }
    </style>

    <link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
    <script src="js/vue.js"></script>
    <script src="element-ui/lib/index.js"></script>
    <script src="js/axios-0.18.0.js"></script>
    <script src="js/server.js" ></script>
    <script type="text/javascript" src="js/echarts.min.js"></script>

</head>
<body>
<div id="div">
    <el-container>
        <!--头部区域-->
        <el-header class="el-header" style="height: 60px">
            <!--水平排列，根据el-container的特点，添加该组件-->
            <el-container>
                <!--logo图片-->
                <div>
                    <el-image src="img/buy.png" class="header-img"></el-image>
                    <div style="margin-top: 20px;float: left;float: right;color: white;font-family: 微软雅黑">超市账单管理系统</div>
                </div>
                <!--顶部导航-->
                <el-dropdown style="margin-left: auto;padding-right: 20px">
					<span class="el-dropdown-link">
						<img :src="loginUser.headUrl || 'img/face.png'" class="face"/>
						<div class="text" v-if="loginUser && loginUser.role">{{loginUser.role.roleName}}:{{loginUser.userCode}}, 欢迎您<i class="el-icon-arrow-down el-icon--right"></i></div>
						<div class="text" v-else>{{loginUser.userCode || '用户'}}, 欢迎您<i class="el-icon-arrow-down el-icon--right"></i></div>
					</span>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="showEditUserView()">个人资料</el-dropdown-item>
						<el-dropdown-item divided @click.native="showEditPwdView()">密码修改</el-dropdown-item>
                        <el-dropdown-item divided @click.native="logout()">注销退出</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </el-container>
        </el-header>
        <el-container style="height: 650px; border: 1px solid #eee">
            <!--侧边栏区域-->
            <el-aside width="200px" style="background-color: rgb(238, 241, 246)" id="aside">
                <el-menu :default-openeds="['0','1','2','3']">
                    <!-- 首页菜单项 -->
                    <el-menu-item index="0" @click="toHtml('welcome.html')">
                        <i class="el-icon-s-home"></i>
                        <span slot="title">首页</span>
                    </el-menu-item>
                    <el-submenu index="1">
                        <template slot="title"><i class="el-icon-menu"></i>供应商管理</template>
                            <el-menu-item index="1-1" @click="toHtml('providerAdd.html')">
                                <i class="el-icon-help"></i>添加供应商
							</el-menu-item>
                            <el-menu-item index="1-2"  @click="toHtml('providerList.html')">
                                <i class="el-icon-help"></i>供应商列表
							</el-menu-item>
                    </el-submenu>
                    <el-submenu index="2">
                        <template slot="title"><i class="el-icon-menu"></i>账单管理</template>
                            <el-menu-item index="2-1" @click="toHtml('billAdd.html')">
                                <i class="el-icon-help"></i>添加账单
                            </el-menu-item>
                            <el-menu-item index="2-2" @click="toHtml('billList.html')">
								<i class="el-icon-help"></i>账单列表
                            </el-menu-item>
                    </el-submenu>
                    <!-- 用户管理菜单，仅管理员可见 -->
                    <el-submenu index="3" v-if="isAdmin">
                        <template slot="title"><i class="el-icon-menu"></i>用户管理</template>
                            <el-menu-item index="3-1" @click="toHtml('userAdd.html')">
                                <i class="el-icon-help"></i>添加用户
                            </el-menu-item>
							<el-menu-item index="3-2" @click="toHtml('userList.html')">
							    <i class="el-icon-help"></i>用户列表
							</el-menu-item>
                    </el-submenu>
                </el-menu>
            </el-aside>
            <!--主区域-->
            <el-container>
                <el-main>
                    <div v-if="iframeSrc === 'welcome.html' || iframeSrc === ''">
                        <!-- 首页统计数据区域 -->
                        <el-row>
                            <el-col :span="6">
                                <el-card shadow="hover" style="width: 100%;">
                                    <div slot="header" class="clearfix">
                                        <span><i class="el-icon-s-flag" style="color: red"></i>今日账单数</span>
                                    </div>
                                    <div style="font-size: 18px;text-align: center; margin-top: 15px;">
                                        {{todaycount}} 笔
                                    </div>
                                    <div style="margin-top: 15px;"></div>
                                </el-card>
                            </el-col>
                            <el-col :span="6">
                                <el-card shadow="hover" style="width: 100%;">
                                    <div slot="header" class="clearfix">
                                        <span><i class="el-icon-s-flag" style="color: yellow"></i>昨日账单数</span>
                                    </div>
                                    <div style="font-size: 18px;text-align: center; margin-top: 15px;">
                                        {{yesterdaycount}} 笔
                                    </div>
                                    <div style="margin-top: 15px;"></div>
                                </el-card>
                            </el-col>
                            <el-col :span="6">
                                <el-card shadow="hover" style="width: 100%;">
                                    <div slot="header" class="clearfix">
                                        <span><i class="el-icon-s-flag" style="color: blue"></i>本周账单数</span>
                                    </div>
                                    <div style="font-size: 18px;text-align: center; margin-top: 15px;">
                                        {{weekcount}} 笔
                                    </div>
                                    <div style="margin-top: 15px;"></div>
                                </el-card>
                            </el-col>
                            <el-col :span="6">
                                <el-card shadow="hover" style="width: 100%;">
                                    <div slot="header" class="clearfix">
                                        <span><i class="el-icon-s-flag" style="color: green"></i>本月账单数</span>
                                    </div>
                                    <div style="font-size: 18px;text-align: center; margin-top: 15px;">
                                        {{monthcount}} 笔
                                    </div>
                                    <div style="margin-top: 15px;"></div>
                                </el-card>
                            </el-col>
                        </el-row>
                        <div style="margin-top: 25px;"></div>
                        <el-row>
                            <el-col :span="12">
                                <el-card shadow="hover" style="width: 100%;">
                                    <div slot="header" class="clearfix">
                                        <span><i class="el-icon-top-right" style="color: red"></i>最近7天账单数量趋势</span>
                                    </div>
                                    <div id="container1" style="height: 300px; font-size: 18px;text-align: center;">
                                    </div>
                                </el-card>
                            </el-col>
                            <el-col :span="12">
                                <el-card shadow="hover" style="width: 100%;">
                                    <div slot="header" class="clearfix">
                                        <span><i class="el-icon-s-data" style="color: green"></i>最近7天账单金额趋势</span>
                                    </div>
                                    <div id="container2" style="height: 300px; font-size: 18px;text-align: center;">
                                    </div>
                                </el-card>
                            </el-col>
                        </el-row>
                    </div>
                    
                    <!-- 其他页面通过iframe加载 -->
                    <iframe v-else id="myframe" false="false" :src="iframeSrc" scrolling="none" frameborder="0"
                            style="top:80px;left: 120px; width: 100%;height:600px"></iframe>
                </el-main>
            </el-container>
            
        </el-container>
    </el-container>
	
	<!-- 个人资料 -->
	<el-dialog title="个人资料" :visible.sync="userEditFormVisible">
	  <el-form :model="userEditForm" ref="userEditForm">
			<el-form-item label="用户名称" prop="userName" :label-width="formLabelWidth">
			    <el-input v-model="userEditForm.userName"></el-input>
			</el-form-item>
			<el-form-item label="性别" prop="gender" :label-width="formLabelWidth">
			    <el-radio v-model="userEditForm.gender" label="1" >男</el-radio>
			    <el-radio v-model="userEditForm.gender" label="2" >女</el-radio>
			</el-form-item>
			<el-form-item label="出生日期" prop="birthday" :label-width="formLabelWidth">
				<el-date-picker
				  v-model="userEditForm.birthday"
				  type="date"
				  placeholder="选择日期"
				  value-format="yyyy-MM-dd" >
				</el-date-picker>
			</el-form-item>
			
			<el-form-item label="手机" prop="phone" :label-width="formLabelWidth">
			    <el-input v-model="userEditForm.phone"></el-input>
			</el-form-item>
			<el-form-item label="地址" prop="address" :label-width="formLabelWidth">
			    <el-input  v-model="userEditForm.address"></el-input>
			</el-form-item>
			<el-form-item label="用户头像" prop="headUrl" :label-width="formLabelWidth">
			    <el-upload
						size="mini"
						class="avatar-uploader"
						v-bind:action="requestUrl"
						:show-file-list="false"
						:on-success="handleAvatarSuccess"
						:before-upload="beforeAvatarUpload">
					<img v-if="userEditForm.headUrl" :src="userEditForm.headUrl" class="avatar">
					<i v-else class="el-icon-plus avatar-uploader-icon"></i>
				</el-upload>
			</el-form-item>
	  </el-form>
	  <div slot="footer" class="dialog-footer">
			<el-button @click="userEditFormVisible = false">取 消</el-button>
	        <el-button type="primary" @click="doUpdateUser()">确 定</el-button>
      </div>
	</el-dialog>
	
	<!-- 密码修改 -->
	<el-dialog title="密码修改" :visible.sync="pwdEditFormVisible">
	  <el-form :model="pwdEditForm" :rules="pwdEditRules" ref="pwdEditForm">
			<el-form-item label="旧密码" prop="userPassword" :label-width="formLabelWidth">
			    <el-input type="password" v-model="pwdEditForm.userPassword"></el-input>
			</el-form-item>
			<el-form-item label="新密码" prop="newPwd" :label-width="formLabelWidth">
			    <el-input  type="password"  v-model="pwdEditForm.newPwd"></el-input>
			</el-form-item>
			<el-form-item label="确认密码" prop="confirmNewPwd" :label-width="formLabelWidth">
			    <el-input type="password"  v-model="pwdEditForm.confirmNewPwd" ></el-input>
			</el-form-item>
	  </el-form>
	  <div slot="footer" class="dialog-footer">
			<el-button @click="pwdEditFormVisible = false">取 消</el-button>
	        <el-button type="primary" @click="doUpdatePwd('pwdEditForm')">确 定</el-button>
      </div>
	</el-dialog>
</div>
</body>
</html>
<script>
    <!-- 首页统计数据相关组件 -->
    var chartInit = {
        initCharts: function() {
            // 7天账单数量趋势图表
            if (document.getElementById('container1')) {
                axios.get(
                    server_url + "/welcome/last7DaysBillCount"
                ).then(resp => {
                    if (resp.data.flag) {
                        // 提取日期和数量数据
                        let dates = [];
                        let counts = [];
                        resp.data.data.forEach(item => {
                            // 格式化日期为MM-DD格式
                            const dateObj = new Date(item.date);
                            const month = dateObj.getMonth() + 1;
                            const day = dateObj.getDate();
                            const formattedDate = month + '-' + day;
                            
                            dates.push(formattedDate);
                            counts.push(item.count);
                        });
                        
                        // 初始化图表
                        let chart1 = echarts.init(document.getElementById('container1'));
                        chart1.setOption({
                            xAxis: {
                                type: 'category',
                                data: dates
                            },
                            yAxis: {
                                type: 'value'
                            },
                            series: [
                                {
                                    data: counts,
                                    type: 'line'
                                }
                            ]
                        });
                    }
                }).catch(err => {
                    console.log(err);
                });
            }
            
            // 7天账单金额趋势图表
            if (document.getElementById('container2')) {
                axios.get(
                    server_url + "/welcome/last7DaysBillAmount"
                ).then(resp => {
                    if (resp.data.flag) {
                        // 提取日期和金额数据
                        let dates = [];
                        let amounts = [];
                        resp.data.data.forEach(item => {
                            // 格式化日期为MM-DD格式
                            const dateObj = new Date(item.date);
                            const month = dateObj.getMonth() + 1;
                            const day = dateObj.getDate();
                            const formattedDate = month + '-' + day;
                            
                            dates.push(formattedDate);
                            amounts.push(item.amount);
                        });
                        
                        // 初始化图表
                        let chart2 = echarts.init(document.getElementById('container2'));
                        chart2.setOption({
                            xAxis: {
                                type: 'category',
                                data: dates
                            },
                            yAxis: {
                                type: 'value'
                            },
                            series: [
                                {
                                    data: amounts,
                                    type: 'bar',
                                    showBackground: true,
                                    backgroundStyle: {
                                        color: 'rgba(180, 180, 180, 0.2)'
                                    }
                                }
                            ]
                        });
                    }
                }).catch(err => {
                    console.log(err);
                });
            }
        }
    };
	
    // 登录成功后根据用户权限,除了系统管理员才能操作用户管理模块
    new Vue({
            el: '#div',
            data: {
                url: 'img/img.jpg',
                iframeSrc: 'welcome.html',
				formLabelWidth: '120px', //设置对话框输入框的宽度
				isAdmin: false, // 是否为管理员
				//个人资料
				userEditFormVisible:false,
				userEditForm:{
					gender: '1',
					headUrl: 'img/face.png'
				},
				//密码修改
				pwdEditFormVisible:false,
				pwdEditForm:{
					userPassword:'',
					newPwd:'',
					confirmNewPwd:''
				},
				pwdEditRules: {
					userPassword: [{
						required: true,
						message: '请输入旧密码',
						trigger: 'blur'
					}],
					newPwd: [{
						required: true,
						message: '请输入新密码',
						trigger: 'blur'
					}],
					confirmNewPwd: [{
						required: true,
						message: '请输入确认密码',
						trigger: 'blur'
					}]
				},
				loginUser:{
					role: {
						roleName: ""
					},
					userCode:""
				},
				requestUrl: server_url + "/user/upload",
                // 首页统计数据
                todaycount: 0,
                yesterdaycount: 0,
                weekcount: 0,
                monthcount: 0
            },
            methods: {
				// 检查用户是否为管理员角色
				isAdminRole(user) {
					// 检查直接角色ID (数据库中admin角色ID为1)
					if (user.userRole === 1 || user.userRole === "1") {
						console.log("通过userRole判断为管理员");
						return true;
					}
					
					// 检查角色对象(如果存在)
					if (user.role) {
						if (user.role.id === 1 || user.role.id === "1") {
							console.log("通过role.id判断为管理员");
							return true;
						}
						
						// 检查角色名称是否包含"管理员"
						if (user.role.roleName && 
							(user.role.roleName.includes("管理员") || 
							 user.role.roleName.toLowerCase().includes("admin"))) {
							console.log("通过roleName判断为管理员");
							return true;
						}
					}
					
					// 通过用户代码判断
					if (user.userCode === "admin") {
						console.log("通过userCode判断为管理员");
						return true;
					}
					
					return false;
				},

				//左侧导航到HTML页面
                toHtml(page){
					//解决iframe缓存问题
					let time=new Date().getTime();
					this.iframeSrc = page + "?t="+time;
					
					// 如果是导航到首页，重新加载统计数据和图表
					if(page === 'welcome.html') {
						// 加载统计数据
						this.loadStatData();
						// 延迟加载图表，确保DOM已经准备好
						setTimeout(() => {
							chartInit.initCharts();
						}, 500);
					}
				},
				showEditUserView(){
                	//1.显示对话框
					this.userEditFormVisible = true;
					//2.取出本地存储的数据转换为json对象再显示页面
					var loginUserStr = localStorage.getItem("loginUser");
					if(null != loginUserStr && "" != loginUserStr){
						//将json字符串转换为json对象
						var loginUser = JSON.parse(loginUserStr);
						// 复制用户数据到编辑表单
						this.userEditForm = {...loginUser};
						// 确保性别是字符串类型
						if (this.userEditForm.gender !== null && this.userEditForm.gender !== undefined) {
							this.userEditForm.gender = this.userEditForm.gender.toString();
						} else {
							this.userEditForm.gender = "1";  // 默认值
						}
						// 确保有头像URL
						if (!this.userEditForm.headUrl) {
							this.userEditForm.headUrl = "img/face.png";
						}
					}
				},
				//上传成功
				handleAvatarSuccess(res, file) {
					console.log(res);
					console.log(file);
					// 调整为与后端返回格式一致
					if (res.code === "00") {
						this.userEditForm.headUrl = res.data;
					} else {
						this.$message.error(res.msg || "上传失败");
					}
					console.log(this.userEditForm.headUrl);
				},
				//上传前准备
				beforeAvatarUpload(file) {
					const isJPG = file.type === 'image/jpeg';
					const isLt2M = file.size / 1024 / 1024 < 2;

					if (!isJPG) {
						this.$message.error('上传头像图片只能是 JPG 格式!');
					}
					if (!isLt2M) {
						this.$message.error('上传头像图片大小不能超过 2MB!');
					}
					return isJPG && isLt2M;
				},
				doUpdateUser(){
					//发送请求
					axios.post(
							server_url + "/user/update",
							this.userEditForm
                 ).then(resp=>{
                     if(resp.data.flag){
							//提示成功信息
							this.$message({
								message: resp.data.message,
								type: 'success'
							});
							//隐藏对话框
							this.userEditFormVisible = false;
							console.log(this.userEditForm);
							//更新本地存储中的用户数据
							localStorage.setItem("loginUser", JSON.stringify(this.userEditForm));
                     }
                 }).catch(err=>{
                     console.log(err);
                 })
				},
				
				showEditPwdView(){
					this.pwdEditFormVisible = true;
				},
				doUpdatePwd(formName){
					this.$refs[formName].validate((valid) => {
						if (valid) {
							if(this.pwdEditForm.newPwd != this.pwdEditForm.confirmNewPwd){
								this.$message.warning("新密码和确认密码不一致,请重新输入");
							}else{
								var loginUser = JSON.parse(localStorage.getItem("loginUser")); //将localstorage中的json字符串转换为json对象
								//发送请求到服务端 用户ID,旧密码,新密码
								axios.post(
										server_url + "/user/updatePassword",
										null,
										{
											params: {
												id: loginUser.id,
												userPassword: this.pwdEditForm.userPassword,
												newPwd: this.pwdEditForm.newPwd
											}
										}
                 ).then(resp=>{
                     if(resp.data.flag){
										//给出成功提示
										this.$message({
											message: resp.data.message,
											type: 'success',
											onClose: this.logout  //成功提示3秒后调用退出函数发送退出请求到服务端然后跳转登录页面
										});
									}else{
										this.$message.error(resp.data.message);
									}

                 }).catch(err=>{
                     console.log(err);
								})
							}
						}
					});
				},
				
				logout(){
					//请求后台，在Servlet中注销用户
					axios({
						method: 'get',
						url: server_url + "/user/logout",
						withCredentials: true
					}).then(resp => {
						console.log('注销响应:', resp.data);
						//清除本地存储的数据
						localStorage.removeItem("loginUser");
						//跳转到登录页面
						window.location.href = "login.html";
					}).catch(err => {
						console.error('注销失败:', err);
						//即使失败也清除本地存储的数据
						localStorage.removeItem("loginUser");
						//跳转到登录页面
						window.location.href = "login.html";
					});
				},
				
				// 检查登录状态
				checkLoginStatus() {
					axios({
						method: 'get',
						url: server_url + "/user/current",
						withCredentials: true
					}).then(resp => {
						console.log('用户状态检查:', resp.data);
						if (!resp.data.flag) {
							// 后端认为用户未登录，清除本地信息并重定向
							this.$message.error(resp.data.message || "登录已过期，请重新登录");
							localStorage.removeItem("loginUser");
							setTimeout(() => {
								window.location.href = "login.html";
							}, 1000);
						}
					}).catch(err => {
						console.error('用户状态检查错误:', err);
					});
				},
                
                // 加载统计数据
                loadStatData() {
                    axios.get(
                        server_url + "/welcome/statBillCount"
                    ).then(resp => {
                        if (resp.data.flag) {
                            //将后端响应的结果获取出来后赋值给vue中data的变量
                            this.todaycount = resp.data.data.todaycount;
                            this.yesterdaycount = resp.data.data.yesterdaycount;
                            this.weekcount = resp.data.data.weekcount;
                            this.monthcount = resp.data.data.monthcount;
                        }
                    }).catch(err => {
                        console.log(err);
                    })
                }
            },
			mounted: function() {
				var loginUserStr = localStorage.getItem("loginUser");
				if(loginUserStr != null && "" != loginUserStr) {
					this.loginUser = JSON.parse(loginUserStr);
					
					// 设置默认头像
					if(this.loginUser.headUrl == null || this.loginUser.headUrl == "") {
						this.loginUser.headUrl = "img/face.png";
					}
					
					// 判断是否为管理员
					console.log("当前用户完整信息:", this.loginUser);
					console.log("用户角色对象:", this.loginUser.role);
					console.log("用户角色ID:", this.loginUser.userRole);
					
					// 使用辅助方法判断是否为管理员
					this.isAdmin = this.isAdminRole(this.loginUser);
					console.log("是否为管理员:", this.isAdmin);
					
					// 检查后端会话状态
					this.checkLoginStatus();
                    
                    // 加载首页统计数据
                    this.loadStatData();
                    
                    // 初始化图表
                    setTimeout(() => {
                        chartInit.initCharts();
                    }, 500);
				} else {
					// 没有本地登录信息，重定向到登录页
					window.location.href = "login.html";
				}
			}
        }
    );
</script>